<template>
  <div class="product-container">
    <div class="search-section animate__animated animate__fadeInDown">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.productName" placeholder="请输入商品名称" prefix-icon="el-icon-goods"></el-input>
        </el-form-item>
        <el-form-item label="价格区间">
          <el-input-number v-model="searchForm.minPrice" :min="0" :precision="2" placeholder="最低价"></el-input-number>
          <span class="price-separator">-</span>
          <el-input-number v-model="searchForm.maxPrice" :min="0" :precision="2" placeholder="最高价"></el-input-number>
        </el-form-item>
        <el-form-item label="原产地">
          <el-input v-model="searchForm.origin" placeholder="请输入原产地"></el-input>
        </el-form-item>
        <el-form-item label="温度范围">
          <el-input-number v-model="searchForm.minTemp" :min="-50" :max="50" placeholder="最低温度"></el-input-number>
          <span class="temp-separator">-</span>
          <el-input-number v-model="searchForm.maxTemp" :min="-50" :max="50" placeholder="最高温度"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="load" icon="el-icon-search">搜索</el-button>
          <el-button @click="reset" icon="el-icon-refresh">重置</el-button>
          <el-button type="success" @click="handleAdd" icon="el-icon-plus">添加商品</el-button>
          <el-button type="danger" @click="handleDelete" icon="el-icon-delete">批量删除</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-section animate__animated animate__fadeInUp">
      <el-table
          :data="tableData" 
          border 
          stripe
          v-loading="loading"
          :header-cell-style="getRowClass"
          @selection-change="handleSelectionChange"
          row-key="id">
        
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="productId" label="商品ID" width="120"></el-table-column>
        <el-table-column prop="productName" label="商品名称" min-width="150">
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.description" placement="top" :disabled="!scope.row.description">
              <span>{{ scope.row.productName }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="traceCode" label="溯源码" width="180">
          <template slot-scope="scope">
            <el-tag size="small" type="info">{{ scope.row.traceCode }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="120">
          <template slot-scope="scope">
            <span class="price">¥{{ scope.row.price.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="origin" label="原产地" width="120"></el-table-column>
        <el-table-column label="温度范围" width="150">
          <template slot-scope="scope">
            <el-tag size="small" type="warning">{{ scope.row.minTemp }}°C</el-tag>
            <span class="temp-separator">-</span>
            <el-tag size="small" type="danger">{{ scope.row.maxTemp }}°C</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="harvestTime" label="收割时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.harvestTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template slot-scope="scope">
            <el-button-group class="operation-buttons">
              <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="mini" type="info" icon="el-icon-view" @click="handleViewDetails(scope.row)">详情</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="block" style="padding:10px 0;align-content: center;margin-left: 30%;margin-top:30px;">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </div>

    <el-dialog :title="form.productId ? '编辑商品' : '添加商品'" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="商品ID" prop="productId" v-if="form.productId">
          <el-input v-model="form.productId" disabled></el-input>
        </el-form-item>
        <el-form-item label="溯源码" prop="traceCode">
          <el-input v-model="form.traceCode" placeholder="可留空由系统自动生成"></el-input>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="form.price" :min="0" :precision="2"></el-input-number>
        </el-form-item>
        <el-form-item label="原产地" prop="origin">
          <el-input v-model="form.origin"></el-input>
        </el-form-item>
        <el-form-item label="最低温度" prop="minTemp">
          <el-input-number v-model="form.minTemp" :min="-50" :max="50"></el-input-number>
        </el-form-item>
        <el-form-item label="最高温度" prop="maxTemp">
          <el-input-number v-model="form.maxTemp" :min="-50" :max="50"></el-input-number>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description"></el-input>
        </el-form-item>
        <el-form-item label="收割时间" prop="harvestTime">
          <el-date-picker
            v-model="form.harvestTime"
            type="datetime"
            placeholder="选择收割时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import 'animate.css/animate.min.css';

export default {
  name: "Product",
  data() {
    return {
      pageSize: 10,
      pageNum: 1,
      productName: '',
      minTemp: null,
      maxTemp: null,
      tableData: [],
      dialogFormVisible: false,
      form: {},
      total: 0,
      multipleSelection: [],
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' }
        ],
        minTemp: [
          { required: true, message: '请输入最低温度', trigger: 'blur' }
        ],
        maxTemp: [
          { required: true, message: '请输入最高温度', trigger: 'blur' }
        ]
      },
      searchForm: {
        productName: '',
        minPrice: 0,
        maxPrice: 0,
        origin: '',
        minTemp: null,
        maxTemp: null
      },
      loading: false
    }
  },
  created() {
    this.load();
  },
  methods: {
    load() {
      this.request.get("/product/list").then(res => {
        if (res.code === '200') {
          // 确保每个商品对象都有productId字段
          this.tableData = res.data.map(item => {
            // 如果后端返回product_id而不是productId，需要进行映射
            if (!item.productId && item.product_id) {
              item.productId = item.product_id;
            }
            
            // 如果productId还是null，使用traceCode作为临时ID
            if (!item.productId && item.traceCode) {
              // 警告日志和告知用户
              console.warn(`商品 ${item.productName} 的productId为空，使用traceCode作为临时ID`);
              item.tempId = item.traceCode; // 使用tempId存储，不直接覆盖productId
              
              // 请求服务器获取或生成真实的productId
              this.request.get(`/product/getIdByTraceCode/${item.traceCode}`).then(idRes => {
                if (idRes.code === '200' && idRes.data) {
                  item.productId = idRes.data;
                  console.log(`商品 ${item.productName} 获取到真实ID: ${item.productId}`);
                }
              }).catch(err => {
                console.error('获取商品ID失败:', err);
              });
            }
            
            // 调试输出商品的完整信息
            console.log('商品数据样例:', JSON.stringify(item));
            
            return item;
          });
          
          this.total = res.data.length;
        }
      });
    },
    getRowClass({rowIndex, columnIndex}) {
      if(rowIndex === 0) {
        return 'background:#ccc'
      }
    },
    reset() {
      this.searchForm = {
        productName: '',
        minPrice: 0,
        maxPrice: 0,
        origin: '',
        minTemp: null,
        maxTemp: null
      };
      this.load();
    },
    handleAdd() {
      this.form = {
        name: '',              // 对应后端Product实体中的name字段
        price: 0,
        origin: '',
        minTemp: 0,
        maxTemp: 0,
        description: '',
        harvestTime: new Date(),
        traceCode: ''          // 添加缺失的traceCode字段
      };
      this.dialogFormVisible = true;
    },
    handleDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的数据');
        return;
      }
      this.$confirm('确定要删除选中的数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 获取所有选中项的ID
        const ids = this.multipleSelection.map(item => item.productId);
        // 调用批量删除API
        this.request.post("/product/delete/batch", ids).then(res => {
          if (res.code === '200') {
            this.$message.success('删除成功');
            this.load();
          } else {
            this.$message.error(res.msg || '删除失败');
          }
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    handleEdit(row) {
      this.form = {
        productId: row.productId,
        name: row.productName,  // 前端展示用productName，后端用name
        price: row.price,
        origin: row.origin,
        minTemp: row.minTemp,
        maxTemp: row.maxTemp,
        description: row.description,
        harvestTime: row.harvestTime,
        traceCode: row.traceCode // 添加溯源码字段
      };
      this.dialogFormVisible = true;
    },
    handleSave() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.productId) {
            // 更新操作 - 直接使用form数据
            this.request.put("/product/update", this.form).then(res => {
              if (res.code === '200') {
                this.$message.success('更新成功');
                this.dialogFormVisible = false;
                this.load();
              } else {
                this.$message.error(res.msg || '更新失败');
              }
            });
          } else {
            // 添加操作 - 确保包含所有必要字段
            // 如果traceCode为空，可以生成一个随机值或暂时留空
            if (!this.form.traceCode) {
              this.form.traceCode = 'TC' + Date.now(); // 简单的临时生成方式
            }
            
            this.request.post("/product/save", this.form).then(res => {
              if (res.code === '200') {
                this.$message.success('添加成功');
                this.dialogFormVisible = false;
                this.load();
              } else {
                this.$message.error(res.msg || '添加失败');
              }
            });
          }
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.load();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.load();
    },
    formatDate(date) {
      return date ? new Date(date).toLocaleString() : '';
    },
    handleViewDetails(row) {
      // 实现查看详情逻辑
      console.log('查看详情:', row);
    }
  }
}
</script>

<style scoped>
.product-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.search-section {
  margin-bottom: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.operation-buttons {
  display: inline-flex;
  white-space: nowrap;
}

.operation-buttons .el-button {
  padding: 5px 8px;
  font-size: 12px;
}

.operation-buttons .el-button [class*="el-icon-"] {
  margin-right: 3px;
}

.operation-buttons .el-button + .el-button {
  margin-left: -1px;
  border-left-color: rgba(255, 255, 255, 0.5);
}

.el-table {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.temp-separator {
  margin: 0 5px;
  color: #909399;
}

.price-separator {
  margin: 0 5px;
  color: #909399;
}

.el-tag {
  margin-left: 5px;
}

/* 移除之前的响应式样式 */
@media screen and (max-width: 768px) {
  .operation-buttons {
    display: inline-flex;
  }
  
  .operation-buttons .el-button {
    padding: 5px 8px;
  }
}

/* 添加动画效果 */
.el-table__row {
  transition: all 0.3s;
}

.el-table__row:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

/* 优化分页样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 添加加载动画 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}
</style>
